#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <pthread.h>
#include "include.h"

//-----------------------------------------------------------------------------

struct thr2* search(size_t id, struct block thr_block){
	pthread_t* thread = (pthread_t*)malloc(thr_block.n*sizeof(pthread_t));
  	int iret;

	struct thr1* tmp = (struct thr1*)malloc(thr_block.n*sizeof(struct thr1));
	struct thr2* k = (struct thr2*)malloc(sizeof(struct thr2));
	k->two = 0;
	size_t i;

	k->three = 0;
	for(i = 0; i < thr_block.n; i++){
		tmp[i].one = thr_block.st[i];
		tmp[i].two = thr_block.sz[i];
		tmp[i].three = id;
 		iret = pthread_create(&thread[i],NULL,fsearch, (void*)(&tmp[i]));
		}

	for(i = 0; i < thr_block.n; i++){
		pthread_join(thread[i],NULL);
			}

	for(i = 0; i < thr_block.n; i++){
		k->three += tmp[i].two;
		if(tmp[i].three) break;
		}

	if(i == thr_block.n){
		k->two = 1;
		free(thread);
		free(tmp);
		return k;
		}
		
	if((tmp[i].one)->rl) k->two = 2;
	else k->two = 0;
	
	k->one = tmp[i].one;
	k->four = i; 
	
	free(thread);
	free(tmp);
	return k; 
};

//-----------------------------------------------------------------------------------------

size_t add(size_t sz, struct block thr_block, size_t id){
	pthread_t* thread = (pthread_t*)malloc(thr_block.n*sizeof(pthread_t));
  	int iret;

	struct thr1* tmp = (struct thr1*)malloc(thr_block.n*sizeof(struct thr1));
	size_t i;

	for(i = 0; i < thr_block.n; i++){
		tmp[i].one = (thr_block.st)[i];
		tmp[i].two = (thr_block.sz)[i];
		tmp[i].three = sz;
 		iret = pthread_create(&thread[i],NULL,fsearch_fr, (void*)(&tmp[i]));
		}

	for(i = 0; i < thr_block.n; i++){
		pthread_join(thread[i],NULL);
			}

	for(i = 0; i < thr_block.n; i++){
		if(tmp[i].three) break;
		}

	if(i == thr_block.n){
		free(thread);
		free(tmp);
		return 0;
		}

	size_t p = fadd(tmp[i].one,sz,id);
	(thr_block.sz)[i] += p;

	free(thread);
	free(tmp);
	return thr_block.n;
};
